package com.ardf.controller;

import com.ardf.common.CodeEnum;
import com.ardf.common.ReturnResult;
import com.ardf.entity.Competition;
import com.ardf.entity.WebSocketEntity;
import com.ardf.service.*;
import com.fazecast.jSerialComm.SerialPort;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/ardf/cardWebsocket")
public class CardWebsocketController {

    @Resource
    private CardWebSocketService cardWebSocketService;

    @Resource
    private ICompetitionService competitionService ;

    @Resource
    private CardPortService cardPortService;

    @Resource
    private IDetailsService detailsService;


    @Resource
    private ICardService cardService;

    @Resource
    private IGradeService gradeService;

    @Resource
    private IAthleteTeamService teamService;

    @Resource
    private IBatchService batchService;

    @Resource
    private IAthleteService athleteService;

    public  List<SerialPort> serialPortList;

    public static String TPNum;



    @PostMapping("/send")
    public ResponseEntity<String> sendMsg(@RequestBody WebSocketEntity req){
        try {
            cardWebSocketService.sendMessageToUser(req.getUid(),req.getMsg());
            System.out.println("接收到请求");
            return ResponseEntity.ok("cardWebSocket open success");
        }catch (Exception e){
            log.error("发送消息失败，req:{},e:{}",req,e.getMessage(),e);
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Request was open");
    }

    @GetMapping("/openPort")
    public  ResponseEntity<ReturnResult> connectPort(@RequestParam("pageSize") Integer pageSize,
                                                     @RequestParam("pageNum") Integer pageNum,
                                                     @RequestParam("unitId") Long unitId,
                                                     @RequestParam("competitionId")Long competitionId){

        serialPortList=cardPortService.discoverSerialPort();

        WebSocketSession session=null;

        for (SerialPort port : serialPortList) {
            System.out.println(port.getPortDescription());
            if (port.getPortDescription().equals("CP2102 USB to UART Bridge Controller")) {
                String result=cardPortService.openSerialPort(cardWebSocketService,port,session,cardService,pageSize,pageNum,unitId,competitionId);
                new ReturnResult(CodeEnum.SUCCESS);
                if(result.equals("串口连接成功")) return ResponseEntity.ok(new ReturnResult(CodeEnum.SUCCESS));

            }
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ReturnResult(CodeEnum.PORT_WAS_OPEN));

    }

    @GetMapping("/closePort")
    public  ResponseEntity<ReturnResult> closePort() {
        if(serialPortList==null){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ReturnResult(CodeEnum.PORT_WAS_CLOSE));
        }
        for (SerialPort port:serialPortList){
            cardPortService.closeSerialPort(port);
            serialPortList=null;
        }
        log.info("串口已关闭");
        return ResponseEntity.ok(new ReturnResult(CodeEnum.SUCCESS));
    }

    /**
     * author:容伟洪
     * time:2025-3-4
     * description：开始比赛的成绩录入请求处理
     */
    @GetMapping("/openGradePort")
    public  ResponseEntity<ReturnResult> connectGradePort(@RequestParam("isRelay") Boolean isRelay,
                                                          @RequestParam("projectId") Long projectId,
                                                          @RequestParam("competitionId")Long competitionId,
                                                          @RequestParam("project")String project){

        serialPortList=cardPortService.discoverSerialPort();
        Competition competition = competitionService.selectById(competitionId);
        WebSocketSession session=null;

        for (SerialPort port : serialPortList) {
            if (port.getPortDescription().equals("CP2102 USB to UART Bridge Controller")) {
                String result=cardPortService.openSerialGradePort(cardWebSocketService,port,session,cardService,gradeService,detailsService,teamService,batchService,projectId,isRelay,competitionId,competition,project);
                new ReturnResult(CodeEnum.SUCCESS);
                if(result.equals("串口连接成功")) return ResponseEntity.ok(new ReturnResult(CodeEnum.SUCCESS));

            }
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ReturnResult(CodeEnum.PORT_WAS_OPEN));

    }

    /**
     * author:容伟洪
     * time:2025-3-8
     * description：补卡请求处理
     */
    @GetMapping("/openReplacePort")
    public  ResponseEntity<ReturnResult> connectReplacePort(@RequestParam("competitionId") Long competitionId,
                                                            @RequestParam("athleteId")Long athleteId){

        serialPortList=cardPortService.discoverSerialPort();

        WebSocketSession session=null;

        for (SerialPort port : serialPortList) {
            if (port.getPortDescription().equals("CP2102 USB to UART Bridge Controller")) {
                String result=cardPortService.openSerialReplacePort(cardWebSocketService,port,session,cardService,athleteService,competitionId,athleteId);
                new ReturnResult(CodeEnum.SUCCESS);
                if(result.equals("串口连接成功")) return ResponseEntity.ok(new ReturnResult(CodeEnum.SUCCESS));
            }
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ReturnResult(CodeEnum.PORT_WAS_OPEN));

    }
}
